package com.lej.core.widget.customview

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.TextView
import androidx.appcompat.widget.AppCompatImageView
import androidx.core.view.isGone
import com.lej.core.R
import com.lej.core.utils.extention.getDrawableCompat

/**
 *  author: cjq
 *  date  : 2022/4/18 0018
 *  desc  : 通用条目
 */
class CustomItemCl @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    private var tvRight: TextView? = null

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.custom_item_rl, this, true)
        attrs?.let { retrieveAttributes(context, it, view) }
    }

    fun setItemTextRight(text: CharSequence?) {
        if (text == null) return
        tvRight?.text = text
    }

    private fun retrieveAttributes(context: Context, attributes: AttributeSet, view: View) {
        val typeArray = context.obtainStyledAttributes(attributes, R.styleable.CustomItemCl)
        val textLeft = typeArray.getText(R.styleable.CustomItemCl_itemTextLeft)
        val textRight = typeArray.getText(R.styleable.CustomItemCl_itemTextRight)
        val drawableRight = typeArray.getDrawable(R.styleable.CustomItemCl_itemDrawableRight)
        val drawableLeft = typeArray.getDrawable(R.styleable.CustomItemCl_itemDrawableLeft)

        val tvLeft = view.findViewById<TextView>(R.id.tv_left)
        tvRight = view.findViewById(R.id.tv_right)
        val iconRight = view.findViewById<AppCompatImageView>(R.id.icon_right)
        val iconLeft = view.findViewById<AppCompatImageView>(R.id.icon_left)

        if (drawableLeft == null) {
            iconLeft.isGone = true
        } else {
            iconLeft.isGone = false
            iconLeft.setImageDrawable(drawableLeft)
        }
        textLeft?.let { tvLeft.text = textLeft }
        textRight?.let { tvRight?.text = textRight }
        iconRight.setImageDrawable(drawableRight ?: context.getDrawableCompat(R.drawable.ic_next))
        typeArray.recycle()
    }
}